package com.ohc.leetcode.数组;

import java.util.*;
import java.util.function.ToIntFunction;

/**
 * https://leetcode-cn.com/problems/intersection-of-two-arrays/
 * 2022年4月11日14:27:03
 */
public class 两个数组的交集349 {

    /**
     * 方法一
     *
     * @param nums1
     * @param nums2
     * @return
     */
    public static int[] intersection1(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < nums1.length; i++) {

            for (int j = 0; j < nums2.length; j++) {
                if (nums1[i] == nums2[j]) {
                    set.add(nums1[i]);
                    continue;
                }
            }
        }
        ArrayList<Integer> list = new ArrayList<>(set);
        int[] ints = list.stream().mapToInt(Integer::valueOf).toArray();
        return ints;
    }


    /**
     * 方法2
     *
     * @param nums1
     * @param nums2
     * @return
     */
    public static int[] intersection2(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();
        for (int i : nums1) {
            set1.add(i);
        }
        for (int i : nums2) {
            if (set1.contains(i)) {
                set2.add(i);
            }
        }
        int[] ints = new int[set2.size()];
        int i = 0;
        for (Integer integer : set2) {
            ints[i++] = integer;
        }
        return ints;
    }


    public static void main(String[] args) {
        int[] nums1 = new int[]{1, 2, 2, 1};
        int[] nums2 = new int[]{2, 2, 1};
        int[] intersection = intersection2(nums1, nums2);
        for (int i = 0; i < intersection.length; i++) {
            System.out.println("intersection[i] = " + intersection[i]);
        }

    }
}
